<?php
/**
 *+------------------
 * Ingenious
 *+------------------
 * Copyright (c) https://gitee.com/ingenstream/ingenious  All rights reserved.
 *+------------------
 * Author: Mr. April (405784684@qq.com)
 *+------------------
 * Software Registration Number: 2024SR0694589
 * Official Website: http://www.ingenstream.cn
 */

namespace madong\think\wf\model;

use madong\ingenious\interface\model\IProcessType;
use madong\think\wf\basic\BaseModel;

class ProcessType extends BaseModel implements IProcessType
{
    /**
     * 数据表主键
     *
     * @var string
     */
    protected $pk = 'id';

    /**
     * 表名
     *
     * @var string
     */
    protected $name = 'wf_process_type';

    /**
     * 是否指定时间戳
     *
     * @var bool
     */
    public $autoWriteTimestamp = true;

    protected $append = ['pid_name', 'create_date', 'update_date'];

    /**
     * 定义访问器
     *
     * @return null
     */
    public function getPidNameAttr($value, $data): mixed
    {
        return $this->parent ? $this->parent->name : '顶级';
    }

    public function searchPidAttr($query, $value)
    {
        if (!empty($value)) {
            $query->where('pid', $value);
        }
    }

    /**
     * 类型名称
     *
     * @param $query
     * @param $value
     */
    public function searchNameAttr($query, $value)
    {

        if (!empty($value)) {
            $query->whereLike('name', '%' . $value . '%');
        }
    }

    /**
     * 是否删除搜索器
     *
     * @param $query
     * @param $value
     */
    public function searchDeleteTimeAttr($query, $value)
    {
        if (!empty($value)) {
            $query->where('delete_time', $value);
        } else {
            $query->where('delete_time', null);
        }
    }

    /**
     * 状态搜索器
     *
     * @param $query
     * @param $value
     */
    public function searchEnabledAttr($query, $value)
    {
        if ($value !== null) {
            $query->where('enabled', $value);
        }
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function parent()
    {
        return $this->hasOne(ProcessType::class, 'id', 'pid');
    }

    /**
     * 类型关联流程定义
     *
     * @return HasMany
     */
    public function items()
    {
        return $this->hasMany(ProcessDefine::class, 'type_id', 'id')->where('enabled', 1);
    }

    public function history()
    {
        return $this->hasMany(ProcessDefine::class, 'type_id', 'id')->where('enabled', 1);
    }

}
